package cn.topcodes.tcsf.admin.web.websocket;

import cn.topcodes.tcsf.admin.domain.entity.SysUser;
import cn.topcodes.tcsf.admin.service.org.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;
import java.util.Map;


public class AdminSessionInterceptor extends HttpSessionHandshakeInterceptor {

    @Autowired
    private SysUserService sysUserService;

    /**
     * 握手前
     * @param request
     * @param response
     * @param wsHandler
     * @param attributes
     * @return
     * @throws Exception
     */
    @Override  
    public boolean beforeHandshake(ServerHttpRequest request,  
            ServerHttpResponse response, WebSocketHandler wsHandler,  
            Map<String, Object> attributes) throws Exception {
        ServletServerHttpRequest req = (ServletServerHttpRequest) request;
        String userId = req.getServletRequest().getParameter("userId");
        try {
            SysUser sysUser = sysUserService.findOne(Long.parseLong(userId));
            if (sysUser != null) {
                attributes.put(AdminSessionEndPoint.USER_ID, userId);
                return super.beforeHandshake(request, response, wsHandler, attributes);
            }
        }catch(Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 握手后
     * @param request
     * @param response
     * @param wsHandler
     * @param ex
     */
    @Override  
    public void afterHandshake(ServerHttpRequest request,  
            ServerHttpResponse response, WebSocketHandler wsHandler,  
            Exception ex) {
        super.afterHandshake(request, response, wsHandler, ex);
    }  
  
}  